class Employee < ActiveRecord::Base
  attr_accessor :new_avatar
  has_one :avatar,
    :as => :attachable,
    :dependent => :destroy,
    :class_name => 'EmployeeAvatar'

  validate :is_avatar_valid?, :validation_field
  after_save :update_avatar

  def uploaded_data=(data)
    p data.type
    @new_avatar = EmployeeAvatar.new(:uploaded_data => data) if data.kind_of? Tempfile
  end

  protected

  def update_avatar
    self.avatar = @new_avatar if @new_avatar
  end

  def is_avatar_valid?
    unless @new_avatar
#      errors.add :avatar, ActiveRecord::Errors.default_error_messages[:blank] if avatar.nil?
      return
    end

    unless @new_avatar.valid?
      @new_avatar.errors.each_full do |msg|
        errors.add :avatar, msg
      end
    end
  end

  def validation_field
    errors.add("Имя", "не может быть пустым") if name.nil? || name == ''
    errors.add("Должность", "должна присутствовать") if job_position.nil? || job_position == ''
    errors.add("Описание", "не может быть пустым") if description.nil? || description == ''
  end

end
